<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import 'element-plus/es/components/message/style/css'
import { VideoPlay, Edit } from '@element-plus/icons-vue'
import { getArticlePronunciation } from '../api/article'
import { getCharacterPinyinList, updateParagraphPinyin } from '../api/pronunciation'

const route = useRoute()
const router = useRouter()

const article = ref({
  id: '',
  title: ''
})

const paragraphs = ref([])
const editDialogVisible = ref(false)
const currentParagraph = ref(null)
const pinyinOptions = ref([])
const selectedCharacter = ref(null)

const loadArticle = async () => {
  try {
    const id = route.query.id
    if (!id) {
      ElMessage.error('文章ID不能为空')
      router.push('/')
      return
    }

    const res = await getArticlePronunciation(id)
    if (res.data && Array.isArray(res.data)) {
      // 按paragraphOrder排序
      paragraphs.value = res.data
        .sort((a, b) => a.paragraph.paragraphOrder - b.paragraph.paragraphOrder)
        .map(item => ({
          id: item.paragraph.id,
          paragraphOrder: item.paragraph.paragraphOrder,
          content: item.paragraph.content,
          words: item.words
        }))
    }
  } catch (error) {
    console.error('加载文章失败：', error)
    ElMessage.error('加载文章失败')
  }
}

const currentUtterance = ref(null)

const stopParagraph = () => {
  if (currentUtterance.value) {
    window.speechSynthesis.cancel()
    currentUtterance.value = null
    // 重置所有段落的高亮状态
    paragraphs.value.forEach(p => {
      p.words.forEach(word => {
        word.isHighlighted = false
      })
    })
  }
}

const playParagraph = (paragraph) => {
  // 如果有正在播放的内容，先停止它
  stopParagraph()

  // 创建语音合成器
  const synth = window.speechSynthesis
  const utterance = new SpeechSynthesisUtterance(paragraph.content)
  utterance.lang = 'zh-CN'
  utterance.rate = 0.8 // 降低语速以提高准确性
  currentUtterance.value = utterance

  // 重置所有高亮状态
  const resetHighlight = () => {
    paragraph.words.forEach(word => {
      word.isHighlighted = false
    })
  }

  // 监听朗读事件
  let lastHighlightTime = 0
  const minHighlightInterval = 50 // 减少高亮间隔以提高响应速度
  let lastCharIndex = -1 // 记录上一次高亮的字符索引

  utterance.onboundary = (event) => {
    if (event.name === 'word') {
      const now = Date.now()
      if (now - lastHighlightTime < minHighlightInterval) {
        return
      }

      // 获取当前字符索引并进行边界检查
      const charIndex = event.charIndex
      if (!paragraph.words || !Array.isArray(paragraph.words)) {
        resetHighlight()
        return
      }

      if (charIndex === undefined || charIndex === null ||
        charIndex < 0 || charIndex >= paragraph.words.length) {
        resetHighlight()
        return
      }

      // 防止重复高亮
      if (charIndex === lastCharIndex) {
        return
      }

      // 更新高亮状态
      resetHighlight()
      paragraph.words[charIndex].isHighlighted = true
      lastCharIndex = charIndex
      lastHighlightTime = now
    }
  }

  // 朗读结束时清除高亮
  utterance.onend = () => {
    resetHighlight()
  }

  synth.speak(utterance)
}

const goBack = () => {
  router.push('/')
}

const handleEditPronunciation = async (paragraph) => {
  // 先深拷贝段落数据
  currentParagraph.value = JSON.parse(JSON.stringify(paragraph))

  // 检测段落中的多音字并标记
  for (const word of currentParagraph.value.words) {
    try {
      // 获取汉字的拼音列表
      const res = await getCharacterPinyinList(word.character)
      const pinyinList = res.data || []

      // 如果拼音列表长度大于1，则标记为多音字
      word.hasMultiplePinyin = pinyinList.length > 1

      // 如果是多音字，设置 isPolyphonic 为 1
      word.isPolyphonic = word.hasMultiplePinyin ? 1 : 0
    } catch (error) {
      console.error(`获取汉字'${word.character}'的拼音列表失败:`, error)
      // 出错时不标记为多音字
      word.hasMultiplePinyin = false
      word.isPolyphonic = 0
    }
  }

  // 打开编辑对话框
  editDialogVisible.value = true
}

const handleCharacterClick = async (word) => {
  try {
    selectedCharacter.value = word
    const res = await getCharacterPinyinList(word.character)
    pinyinOptions.value = res.data || []

    // Check if the word has multiple pinyin options
    word.hasMultiplePinyin = pinyinOptions.value.length > 1
  } catch (error) {
    console.error('获取拼音列表失败：', error)
    ElMessage.error('获取拼音列表失败')
  }
}

const handlePinyinSelect = (pinyin) => {
  if (selectedCharacter.value) {
    selectedCharacter.value.pinyin = pinyin
  }
}

const handleSavePronunciation = async () => {
  try {
    if (!selectedCharacter.value || !selectedCharacter.value.pinyin) {
      ElMessage.warning('请先选择拼音')
      return
    }

    const paragraphData = {
      id: currentParagraph.value.id,
      wordsId: selectedCharacter.value.id,
      selectedCharacter: selectedCharacter.value.pinyin,
    }
    console.log('我 进来了 :')

    await updateParagraphPinyin(paragraphData)

    console.log('我 进来了2 :')

    // 更新paragraphs数组中对应段落的汉字拼音
    const paragraphIndex = paragraphs.value.findIndex(p => p.id === currentParagraph.value.id)
    console.log('我 进来了3 :')
    console.log('paragraphIndex:', paragraphIndex)
    if (paragraphIndex !== -1) {
      const wordIndex = paragraphs.value[paragraphIndex].words.findIndex(w => w.id === selectedCharacter.value.id)
      if (wordIndex !== -1) {
        paragraphs.value[paragraphIndex].words[wordIndex].pinyin = selectedCharacter.value.pinyin
      }
    }

    editDialogVisible.value = false
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存失败：', error)
    ElMessage.error('保存失败')
  }
}

onMounted(() => {
  loadArticle()
})
</script>

<template>
  <div class="pronunciation-edit">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>发音编辑 - {{ article.title }}</span>
          <el-button type="primary" link @click="goBack">返回列表</el-button>
        </div>
      </template>

      <div class="paragraphs-container">
        <div v-for="paragraph in paragraphs" :key="paragraph.id" class="paragraph-item">
          <div class="paragraph-header">
            <span class="paragraph-number">段落 {{ paragraph.paragraphOrder }}</span>
            <el-button type="primary" @click="playParagraph(paragraph)" size="small">
              <el-icon>
                <VideoPlay />
              </el-icon> 播放
            </el-button>
            <el-button type="warning" @click="stopParagraph" size="small" :disabled="!currentUtterance">
              <el-icon>
                <VideoPause />
              </el-icon> 停止
            </el-button>
          </div>
          <div class="paragraph-content">
            <span v-for="(word, index) in paragraph.words" :key="index" class="word"
              :class="{ 'highlighted': word.isHighlighted, 'multiple-pinyin': word.hasMultiplePinyin, 'polyphonic-highlight': word.isPolyphonic === 1 }">
              <span class="character">{{ word.character }}</span>
              <span class="pinyin">{{ word.pinyin }}</span>
            </span>
          </div>
          <div class="paragraph-footer">
            <el-button type="primary" @click="handleEditPronunciation(paragraph)" size="small">
              <el-icon>
                <Edit />
              </el-icon> 编辑声调
            </el-button>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 编辑声调对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑声调" width="80%" :close-on-click-modal="false">
      <div v-if="currentParagraph" class="edit-dialog-content">
        <div class="paragraph-words">

          <span v-for="(word, index) in currentParagraph.words" :key="index" class="word" :class="{
            'selected': selectedCharacter === word,
            'multiple-pinyin': word.hasMultiplePinyin,
            'polyphonic-highlight': word.isPolyphonic === 1
          }" @click="handleCharacterClick(word)">
            <span class="character">{{ word.character }}</span>
            <span class="pinyin">{{ word.pinyin }}</span>
          </span>
        </div>

        <!-- 拼音选择列表 -->
        <div v-if="selectedCharacter && pinyinOptions.length > 0" class="pinyin-options">
          <div class="options-title">选择拼音：</div>
          <el-radio-group v-model="selectedCharacter.pinyin">
            <el-radio v-for="pinyin in pinyinOptions" :key="pinyin" :label="pinyin" border>
              {{ pinyin }}
            </el-radio>
          </el-radio-group>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSavePronunciation">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.pronunciation-edit {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.paragraphs-container {
  margin-top: 20px;
}

.paragraph-item {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
}

.paragraph-header {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.paragraph-number {
  font-weight: bold;
  color: #409EFF;
}

.paragraph-content {
  margin-bottom: 15px;
  line-height: 2;
  font-size: 16px;
}

.paragraph-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}

.word {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  margin: 0 4px;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.3s;
}

.word:hover {
  background-color: #f5f7fa;
}

.word.highlighted {
  background-color: #ffd04b;
  transition: background-color 0.3s ease;
}

.word.selected {
  background-color: #ecf5ff;
  border: 1px solid #409eff;
}

.word.multiple-pinyin {
  background-color: #ffcccc;
  /* Light red background for words with multiple pinyin */
  border: 1px solid #ff0000;
  /* Red border for emphasis */
}

.word.polyphonic-highlight {
  background-color: #d1e7dd; /* Light green background for polyphonic words */
  border: 1px solid #0f5132; /* Dark green border for emphasis */
}

.character {
  font-size: 18px;
}

.pinyin {
  font-size: 12px;
  color: #666;
  margin-top: 2px;
}

.edit-dialog-content {
  padding: 20px;
}

.paragraph-words {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.pinyin-options {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.options-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.el-radio {
  margin-right: 15px;
  margin-bottom: 10px;
}
</style>